package http_proxy_middleware

import (
	"fmt"

	"gin-gateway/middleware"
	"gin-gateway/core/utils"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTPFlowLimitMiddleware 服务限流 和 ip限流
func HTTPFlowLimitMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceDetail := GetServiceDetail(c)

		// 服务限流
		if serviceDetail.AccessControl.ServiceFlowLimit != 0 {
			serviceLimiter, err := utils.FlowLimitManager.GetLimiter(utils.FlowServicePrefix+serviceDetail.Info.ServiceName,
				float64(serviceDetail.AccessControl.ServiceFlowLimit))
			if err != nil {
				middleware.ResponseError(c, 5001, err)
				c.Abort()
				return
			}
			if !serviceLimiter.Allow() {
				middleware.ResponseError(c, 5002, errors.New(fmt.Sprintf("service flow limit %v", serviceDetail.AccessControl.ServiceFlowLimit)))
				c.Abort()
				return
			}
		}

		// ip 限流
		if serviceDetail.AccessControl.ClientIPFlowLimit > 0 {
			clientIpLimiter, err := utils.FlowLimitManager.GetLimiter(utils.FlowServicePrefix+serviceDetail.Info.ServiceName+"_"+c.ClientIP(),
				float64(serviceDetail.AccessControl.ClientIPFlowLimit))
			if err != nil {
				middleware.ResponseError(c, 5003, err)
				c.Abort()
				return
			}
			if !clientIpLimiter.Allow() {
				middleware.ResponseError(c, 5002, errors.New(fmt.Sprintf("%v flow limit %v", c.ClientIP(), serviceDetail.AccessControl.ClientIPFlowLimit)))
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
